package com.fddh.springboot.service.impl;

import com.fddh.springboot.dto.LoginUserDto;
import com.fddh.springboot.dto.UserDto;
import com.fddh.springboot.entity.User;
import com.fddh.springboot.service.LoginService;
import com.fddh.springboot.mapper.UserMapper;
import com.fddh.springboot.util.AESUtil;
import com.fddh.springboot.util.CopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("LoginServiceImpl")    //注释为服务，指定bean名称为LoginServiceImpl
public class LoginServiceImpl implements LoginService {

    private static final Logger LOG = LoggerFactory.getLogger(LoginServiceImpl.class);

    @Autowired
    private UserMapper userMapper;

    /**
     * login
     */
    public LoginUserDto login(UserDto userDto) throws Exception {

        LoginUserDto loginUserDto;
        //get a user from database
        User user = userMapper.getUserByName(userDto.getUsername());//provide a user name from login

        //后台和前台密码解密后，赋值给字符串
        String BackUserPassword = AESUtil.decrypt(user.getPassword());
        String FrontUserPassword = AESUtil.decrypt(userDto.getPassword());

        //登录成功返回给上一层
        if (user == null) {
            LOG.info("用户不存在, {}", userDto.getUsername());
            loginUserDto = null;
        } else {

            if (BackUserPassword.equals(FrontUserPassword)) {
                // 登录成功
                loginUserDto = CopyUtil.copy(user, LoginUserDto.class);
            } else {
                // 密码不正确
                LOG.info("密码不对， 输入密码: {}, 数据库密码: {}", userDto.getPassword(), user.getPassword());
                loginUserDto = null;
            }
        }
        return loginUserDto;
    }
}

